let Sequelize = require('sequelize');
let fs = require('fs');
let Q = require('q');
const logger = require('../lib/logger');

let db = {};

db.init = function (dbConfig) {
    db.sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
        host: dbConfig.host,
        dialect: 'mysql',
        port: dbConfig.port,
        timezone: '+08:00',
        // logging: false
    });
    setModules(db.sequelize);
    logger.data.info('db.init success');
};

db.exec = function (sql, params) {
    let dfd = Q.defer();
    params = params || [];
    db.sequelize.query(sql, params).spread(function (rows) {
        dfd.resolve(rows);
    }).catch(function (err) {
        logger.error.error('db exec err', sql, err);
        dfd.reject(new Error('db exec error'));
    }).done();
    return dfd.promise;
};

function setModules(sequelize) {
    let fileList = fs.readdirSync(`${__dirname}/modules/`);
    fileList.forEach(function (item) {
        db[item.replace('.js', '')] = sequelize.import(`${__dirname}/modules/${item}`);
    });
    /* 设置外键 */
    db.data_source.hasMany(db.grab_source_conf, { foreignKey: 'data_source_id', as: 'grabSourceList' });
    db.grab_source_conf.belongsTo(db.data_source, { foreignKey: 'data_source_id', as: 'dataSource' });

    db.info_type.hasMany(db.grab_source_conf, { foreignKey: 'info_type_id', as: 'grabSourceList' });
    db.grab_source_conf.belongsTo(db.info_type, { foreignKey: 'info_type_id', as: 'infoType' });

    db.category.hasMany(db.grab_source_conf, { foreignKey: 'category_id', as: 'grabSourceList' });
    db.grab_source_conf.belongsTo(db.category, { foreignKey: 'category_id', as: 'category' });

    // db.grab_source_conf.hasMany(db.monitor_conf, { foreignKey: 'station_id', as: 'monitorConfList' });
    // db.monitor_conf.belongsTo(db.grab_source_conf, { foreignKey: 'station_id', as: 'grabSourceConf' });

    db.crawler_storage_model.hasMany(db.monitor_conf, { foreignKey: 'model_id', as: 'monitorConfList' });
    db.monitor_conf.belongsTo(db.crawler_storage_model, { foreignKey: 'model_id', as: 'crawlerStorageModel' });
}

module.exports = db;
